package com.cjw.config.handler;

import cn.hutool.jwt.JWT;
import com.cjw.enums.ErrorCode;
import com.cjw.enums.user.UserType;
import com.cjw.exceptions.BusinessException;
import com.cjw.pojo.dto.database.UserDTO;
import com.cjw.service.database.UserService;
import com.cjw.service.resourceManage.ControllerResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.servlet.HandlerInterceptor;
import com.cjw.util.BaseContextHolder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.Collection;
import java.util.Properties;

@Component
@CrossOrigin
public class UserContextHandler implements HandlerInterceptor {
    @Autowired
    private UserService userService;

    private Properties properties = new Properties();

    @Autowired
    private ControllerResourceService resourceService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        String servletPath = request.getServletPath();
        // 接口封禁，就无法访问
        if (resourceService.getStateByUrl(servletPath) == 0)
            return false;
        // 白名单认证
        InputStream resourceAsStream = UserContextHandler.class.getClassLoader().getResourceAsStream("whiteList.properties");
        properties.load(resourceAsStream);
        Collection<Object> values = properties.values();
        for (Object value : values) {
            if (servletPath.equals((String) value)) {
                return true;
            }
        }

        // 其他访问路径都需要登录，即有token才能访问
        if (StringUtils.hasText(token)) {
            long id = Long.parseLong(JWT.of(token).getPayload("id").toString());
            BaseContextHolder.set("user", userService.queryNormalById(id));
            UserDTO user = (UserDTO) BaseContextHolder.get("user");
            String[] split = servletPath.split("/");
            //设置管理员和用户的管理权限  这个是粗粒度，需要具体某一个资源需要访问，需要比较用户的资源列表和请求url
            //但是由于这样子需要一直对数据库修改资源列表，所以这里并不使用
            if (split[1].equals("user")) {
                if (user.getType() != UserType.USER.getCode())
                    throw new BusinessException(ErrorCode.NOT_AUTHORITY);
            }
            if (split[1].equals("admin")) {
                if (user.getType() != UserType.ADMIN.getCode())
                    throw new BusinessException(ErrorCode.NOT_AUTHORITY);
                return true;
            }
        }
        // 正式部署请输不要注释下面代码
//        else {
//            throw new BusinessException(ErrorCode.NOT_LOGIN);
//        }
        return true;
    }
}
